#include "Square.h"
#include "Node.h"
#include "Mesh.h"
#include "Game.h"
#include <iostream>
using namespace std;

Square::Square(int x, int y, int color) : GameObject()
{
	mPosX = x;
	mPosY = y;
	mColor = color;
	
	BuildMesh();
}

Square::~Square(void)
{
	
}

void Square::BuildMesh()
{
	float vertices[] = {
		-1, -1, 1,
		1, -1, 1,
		-1, 1, 1,
		1, 1, 1,
		-1, -1, -1,
		1, -1, -1,
		-1, 1, -1,
		1, 1, -1,
	};

	int indices[] = {
		0, 1, 3,
		0, 3, 2,
		4, 7, 5,
		4, 6, 7,
		1, 5, 7,
		1, 7, 3,
		0, 2, 6,
		0, 6, 4,
		2, 3, 7,
		2, 7, 6,
		0, 4, 5,
		0, 5, 1,
	};

	Mesh* mesh = new Mesh();

	if (mColor == COLOR_DARK)
	{
		mesh->SetColor(Color(0.5294f, 0.2588f, 0.1216f, 1.0f));
	}
	else
	{
		mesh->SetColor(Color(0.8706f, 0.7216f, 0.5294f, 1.0f));
	}

	VertexBuffer* vb = new VertexBuffer();
	for (int i = 0; i < 8; i++)
	{
		Vertex vtx;
		vtx.position = Vector3(vertices[i*3], vertices[i*3+1], vertices[i*3+2]);
		vb->push_back(vtx);
	}

	IndexBuffer* ib = new IndexBuffer(indices, indices + sizeof(indices)/sizeof(int));

	mesh->SetVertexBuffer(vb);
	mesh->SetIndexBuffer(ib);

	mNode->SetMesh(mesh);

	UpdateTransformation();
}

void Square::UpdateTransformation()
{
	mNode->SetPosition(Vector3((float)mPosX - 0.5f, (float)mPosY - 0.5f, 0));
	mNode->SetScale(Vector3(0.5f, 0.5f, 0.5f));
}

void Square::OnSelect()
{
	Game::GetGame()->MoveToPosition(mPosX, mPosY);
}
